package statis

import (
	//"encoding/json"
	"strconv"
	"strings"
	"time"

	"qkleague/db"
	"qkleague/errorcode"
	//	rpc "qkleague/rpc/client/qingke"

	"github.com/astaxie/beego"
	log "github.com/cihub/seelog"
)

var (
	washModeMap            map[int]string
	qkleaguestatisInstance *QKleagueStatis
)

const (
	APPKEY    = "62ac59ca9ba2415898438c36dcc34f53"
	SECRETKEY = "585d035ae9584f0f84ce6aa1500ed2ab"
	URLBASE   = "https://test00.sz.qkier.com/league"
)

type QKleagueStatis struct{}

func GetQKleagueStatis() *QKleagueStatis {
	if qkleaguestatisInstance == nil {
		qkleaguestatisInstance = &QKleagueStatis{}
	}
	return qkleaguestatisInstance
}

//洗衣房昨日营收:昨日营收，订单数量统计， 错误信息
func (p *QKleagueStatis) QueryWashroomYesProfit(userid, roomid string) (int, int, uint) {
	now := time.Now()
	tmp := now.AddDate(0, 0, -1).Format("2006-01-02 15:04:05")
	day := strings.Split(tmp, " ")[0] //获取昨日的year-month-day
	profit := 0
	total := 0
	sql := "select total_revenue, total_order from washingmode_day where userid = ? and room_id = ? and day = ?"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userid, roomid, day)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, 0, errorcode.EC_GL_INTERNAL_ERROR
	}
	for _, dt := range results {
		order := mysqlHelper.GetColInt(dt, "total_order")
		profit += mysqlHelper.GetColInt(dt, "total_revenue")
		total += order
	}

	return profit, total, errorcode.EC_GL_SUCCESS
}

//洗衣房本月营收:本月截止目前营收，订单数量统计， 错误信息
func (p *QKleagueStatis) QueryWashroomMonProfit(userid, roomid string) (int, int, uint) {
	profit := 0
	total := 0
	now := time.Now().Format("2006-01-02 15:04:05")
	day := strings.Split(now, " ")[0]
	days := strings.Split(day, "-")
	month := days[0] + "-" + days[1]
	sql := "select total_revenue, total_order, wash_mode_id from washingmode_day where userid = ? and room_id = ? and month=?"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userid, roomid, month)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return profit, total, errorcode.EC_GL_INTERNAL_ERROR
	}
	for _, dt := range results {
		order := mysqlHelper.GetColInt(dt, "total_order")
		profit += mysqlHelper.GetColInt(dt, "total_revenue")
		total += order
	}
	return profit, total, errorcode.EC_GL_SUCCESS
}

//洗衣房所有营收
func (p *QKleagueStatis) QueryWashroomAllProfit(userid, roomid string) (int, string, uint) {
	sql := "select sum(total_revenue) as revenue, room_name, userid, room_id from washingmode_day where userid = ? and room_id = ? group by userid, room_id, room_name"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userid, roomid)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, "", errorcode.EC_GL_INTERNAL_ERROR
	}
	if len(results) == 0 {
		return 0, "", errorcode.EC_STATIS_WASHROOM_HAS_NO_ORDER
	}
	profit := mysqlHelper.GetColInt(results[0], "revenue")
	name := mysqlHelper.GetColString(results[0], "room_name")
	return profit, name, errorcode.EC_GL_SUCCESS
}

type proord struct {
	Ypro int `json:"yesterday_profit"`
	Mpro int `json:"month_profit"`
	Apro int `json:"all_profit"`
	Yord int `json:"yesterday_order"`
	Mord int `json:"month_order"`
	Aord int `json:"all_order"`
}

//加盟商首页的盈利-订单统计数据
func (p *QKleagueStatis) QueryUserProfitOrser(userid string) (*proord, uint) {
	yp, yo, ycode := p.QueryUserYesProfit(userid)
	mp, mo, mcode := p.QueryUserMonProfit(userid)
	ap, ao, acode := p.QueryUserAll(userid)
	if ycode == errorcode.EC_GL_SUCCESS && mcode == errorcode.EC_GL_SUCCESS && acode == errorcode.EC_GL_SUCCESS {
		data := &proord{yp, mp, ap, yo, mo, ao}
		return data, errorcode.EC_GL_SUCCESS
	}
	return nil, errorcode.EC_GL_INTERNAL_ERROR
}

//用户昨日营收-遍历洗衣房的昨日营收
func (p *QKleagueStatis) QueryUserYesProfit(userid string) (int, int, uint) {
	yes := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
	sql := "select sum(total_revenue) as profits, sum(total_order) as orders from washingmode_day where userid = ? and day = ?"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userid, yes)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, 0, errorcode.EC_GL_INTERNAL_ERROR
	}
	profit := mysqlHelper.GetColInt(results[0], "profits")
	order := mysqlHelper.GetColInt(results[0], "orders")
	return profit, order, errorcode.EC_GL_SUCCESS
}

//用户本月截止营收
func (p *QKleagueStatis) QueryUserMonProfit(userid string) (int, int, uint) {
	yes := time.Now().Format("2006-01")
	sql := "select sum(total_revenue) as profits, sum(total_order) as orders from washingmode_day where userid = ? and month = ?"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userid, yes)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, 0, errorcode.EC_GL_INTERNAL_ERROR
	}
	profit := mysqlHelper.GetColInt(results[0], "profits")
	order := mysqlHelper.GetColInt(results[0], "orders")
	return profit, order, errorcode.EC_GL_SUCCESS
}

//用户总营收和订单量
func (p *QKleagueStatis) QueryUserAll(userid string) (int, int, uint) {
	sql := "select sum(total_revenue) as allprofit, sum(total_order) as allorders from washingmode_day where userid = ?"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, userid)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, 0, errorcode.EC_GL_INTERNAL_ERROR
	}
	profit := mysqlHelper.GetColInt(results[0], "allprofit")
	/*

		sql = "select sum(total_order) as allorders from washingmode_day where userid = ?"
		results, err = mysqlHelper.Query(sql, userid)
		if err != nil {
			log.Warnf("sql err, err:%s", err.Error())
			return profit, 0, errorcode.EC_GL_INTERNAL_ERROR
		}*/
	orders := mysqlHelper.GetColInt(results[0], "allorders")
	return profit, orders, errorcode.EC_GL_SUCCESS
}

type washMode struct {
	WashModeId   int    `json:"wash_mode_id"`
	WashModeName string `wash_mode_name`
	Num          int    `json:"num"`
}

//订单营收及洗衣模式分析
func (p *QKleagueStatis) AnalyzeProfitOrders(userid string) (int, int, interface{}, interface{}, uint) {
	orders := 0
	profits := 0
	washModeProfitCompare := make(map[int]*washMode)
	washModeOrderCompare := make(map[int]*washMode)
	timeStr := time.Now().Format("2006-01-02")
	t, _ := time.Parse("2006-01-02", timeStr)
	timeNumber := t.Unix()-8*3600
	//sql := "select sum(total_revenue) as profits, sum(total_order) as orders, wash_mode_id, userid from washingmode_day where userid = ? group by userid, wash_mode_id"
	sql :="SELECT sum(price) as profits, COUNT(0) orders, wash_mode_id, league_id FROM washing_order WHERE   order_create_tick<? AND order_create_tick>=? AND league_id=? AND order_status_code=4 GROUP BY league_id ,wash_mode_id"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	//results, err := mysqlHelper.Query(sql, userid)
	results, err := mysqlHelper.Query(sql, timeNumber,timeNumber-86400,userid)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return profits, orders, nil, nil, errorcode.EC_GL_INTERNAL_ERROR
	}
	for _, dt := range results {
		washModeId := mysqlHelper.GetColInt(dt, "wash_mode_id")
		order := mysqlHelper.GetColInt(dt, "orders")
		profit := mysqlHelper.GetColInt(dt, "profits")
		profits += profit
		orders += order
		//排除washModeId=0的情况
		if washModeId == 0 {
			continue
		}
		if _, ok := washModeProfitCompare[washModeId]; !ok {
			washModeName := ""
			if val, ok := washModeMap[washModeId]; ok {
				washModeName = val
			} else {
				washModeName = "new washMode"
			}
			washModeProfitCompare[washModeId] = &washMode{washModeId, washModeName, profit}
		}
		if _, ok := washModeOrderCompare[washModeId]; !ok {
			washModeName := ""
			if val, ok := washModeMap[washModeId]; ok {
				washModeName = val
			} else {
				washModeName = "new washMode"
			}
			washModeOrderCompare[washModeId] = &washMode{washModeId, washModeName, order}
		}
	}
	profitCompare := make([]*washMode, 0)
	orderCompare := make([]*washMode, 0)
	for washModeId, _ := range washModeMap {
		if val, ok := washModeProfitCompare[washModeId]; ok {
			profitCompare = append(profitCompare, val)
		} else { //当没有特定的洗衣模式时,返回0
			profitCompare = append(profitCompare, &washMode{washModeId, washModeMap[washModeId], 0})
		}

		if val, ok := washModeOrderCompare[washModeId]; ok {
			orderCompare = append(orderCompare, val)
		} else {
			orderCompare = append(orderCompare, &washMode{washModeId, washModeMap[washModeId], 0})
		}
	}
	//判断是否出现新的洗衣模式id,但是此时没有映射关系
	for washModeId, val := range washModeProfitCompare {
		if val.WashModeName == "new washMode" {
			profitCompare = append(profitCompare, &washMode{washModeId, "new washMode", 0})
		}
	}
	for washModeId, val := range washModeOrderCompare {
		if val.WashModeName == "new washMode" {
			orderCompare = append(orderCompare, &washMode{washModeId, "new washMode", 0})
		}
	}

	return profits, orders, profitCompare, orderCompare, errorcode.EC_GL_SUCCESS
}

type washroomAnalyze struct {
	Roomid    string `json:"roomid"`
	RoomName  string `json:"room_name"`
	AllProfit int    `json:"all_profit"`
	Allday    int    `json:"all_day"`
	Avaprofit string `json:"ava_profit"`
}

//洗衣房营收分析
func (p *QKleagueStatis) AnalyzeWashroomProfitOrders(userid string) ([]*washroomAnalyze, uint) {
	list := make([]*washroomAnalyze, 0)
	sql := `select room_id, room_name, sum(total_revenue) as profit from washingmode_day where userid = ? group by room_id, room_name`
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	if results, err := mysqlHelper.Query(sql, userid); err == nil {
		for _, dt := range results {
			roomId := mysqlHelper.GetColString(dt, "room_id")
			roomName := mysqlHelper.GetColString(dt, "room_name")
			profit := mysqlHelper.GetColInt(dt, "profit")
			workdays, _ := getWMWorkingDays(roomId)
			if workdays != 0 {
				ava := strconv.FormatFloat((float64(profit) / float64(workdays)), 'f', 2, 64)
				info := &washroomAnalyze{roomId, roomName, profit, workdays, ava}
				list = append(list, info)
			} else {
				info := &washroomAnalyze{roomId, roomName, 0, 0, "0"}
				list = append(list, info)
			}
		}
	} else {
		log.Warnf("AnalyzeWashroomProfitOrders, mysql err, err:%s", err.Error())
		return list, errorcode.EC_GL_INTERNAL_ERROR
	}
	return list, errorcode.EC_GL_SUCCESS
}

type bill struct {
	Userid        string `json:"userid"`
	BillName      string `json:"bill_name"`
	Period        string `json:"period"`
	Profit        int    `json:"profit"`
	Actual        int    `json:"actual"`
	ManageFee     int    `json:"manage_fee"`
	ReductionRate int    `json:"reduction_rate"`
	StatusCode    int    `json:"status_code"`
	Status        string `json:"status_code_des"`
}

//获取用户月账单
func (p *QKleagueStatis) UserMonthBill(userid string) (string, []*bill, uint) {
	billMsg := beego.AppConfig.DefaultString("qkleague::bill_msg", "")
	data := make([]*bill, 0)
	sql := "select userid, bill_name, all_profit, actual_profit, manage_fee, reduction_rate, period, transfer_code, transfer_code_des from user_bill where userid = ? order by id desc"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	result, err := mysqlHelper.Query(sql, userid)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return billMsg, nil, errorcode.EC_GL_INTERNAL_ERROR
	}
	for _, dt := range result {
		info := &bill{}
		info.Userid = mysqlHelper.GetColString(dt, "userid")
		info.BillName = mysqlHelper.GetColString(dt, "bill_name")
		info.Period = mysqlHelper.GetColString(dt, "period")
		info.Profit = mysqlHelper.GetColInt(dt, "all_profit")
		info.Actual = mysqlHelper.GetColInt(dt, "actual_profit")
		info.ManageFee = mysqlHelper.GetColInt(dt, "manage_fee")
		info.ReductionRate = mysqlHelper.GetColInt(dt, "reduction_rate")
		info.StatusCode = mysqlHelper.GetColInt(dt, "transfer_code")
		info.Status = mysqlHelper.GetColString(dt, "transfer_code_des")
		data = append(data, info)
	}
	return billMsg, data, errorcode.EC_GL_SUCCESS
}

//获取洗衣机运转的天数
func getWMWorkingDays(roomid string) (int, error) {
	sql := "select sum(days) as total_day from washer_working_days where room_id = ?"
	mysqlHelper := db.GetQKLeagueMySQLHelper()
	results, err := mysqlHelper.Query(sql, roomid)
	if err != nil {
		log.Warnf("sql err, err:%s", err.Error())
		return 0, err
	}
	days := mysqlHelper.GetColInt(results[0], "total_day")
	return days, nil
}

func init() {
	washModeMap = map[int]string{
		1: "标准洗",
		2: "快速洗",
		3: "强力洗",
		4: "单脱水",
	}
}
